package com.excellent.mvvm.base

import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.flowWithLifecycle
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.ToastUtils
import com.excellent.mvvm.extend.flowLaunch
import java.lang.reflect.ParameterizedType


abstract class BaseVMActivity<VM : BaseViewModel, VB : ViewBinding> : BaseActivity<VB>() {

    open lateinit var viewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        createViewModel()
        lifecycle.addObserver(viewModel)
        //注册 UI事件
        registerDefUIChange()
        super.onCreate(savedInstanceState)
    }

    /**
     * 注册 UI 事件
     */
    private fun registerDefUIChange() {
        flowLaunch {
            viewModel.defUI.showDialog.flowWithLifecycle(lifecycle).collect {
                showLoading(it)
            }
        }
        flowLaunch {
            viewModel.defUI.dismissDialog.flowWithLifecycle(lifecycle).collect {
                dismissLoading()
            }
        }
        flowLaunch {
            viewModel.defUI.msgEvent.flowWithLifecycle(lifecycle).collect {
                handleEvent(it)
            }
        }
        flowLaunch {
            viewModel.defUI.showToast.flowWithLifecycle(lifecycle).collect{
                ToastUtils.showShort(it)
            }
        }
    }

    /**
     * 创建 ViewModel
     */
    @Suppress("UNCHECKED_CAST")
    private fun createViewModel() {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val cls = type.actualTypeArguments[0] as Class<VM>
            viewModel = ViewModelProvider(viewModelStore, defaultViewModelProviderFactory)[cls]
        }
    }

}